package com.example.dakotanews.service.implement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dakotanews.dto.IssueDTO;
import com.example.dakotanews.dto.utils.ApiResponse;
import com.example.dakotanews.dto.utils.ResponseCode;
import com.example.dakotanews.entity.Issue;
import com.example.dakotanews.mapper.IssueMapper;
import com.example.dakotanews.service.IssueService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IssueServiceImpl implements IssueService {
    private final IssueMapper issueMapper;

    public IssueServiceImpl(
            IssueMapper issueMapper
    ) {
        this.issueMapper = issueMapper;
    }

    @Override
    public ApiResponse<Object> getAllIssues() {
        List<Issue> issueList = issueMapper.selectList(new QueryWrapper<>());
        Map<String, Object> data = new HashMap<>();
        if(issueList.size() == 0) {
            return new ApiResponse<>(ResponseCode.NOT_FOUND, "没有话题", null);
        }
        List<IssueDTO> issueDTOList = new ArrayList<>();
        for(Issue issue: issueList) {
            IssueDTO issueDTO = new IssueDTO(issue.getId(), issue.getIssueName());
            issueDTOList.add(issueDTO);
        }
        data.put("issues", issueDTOList);

        return new ApiResponse<>(ResponseCode.SUCCESS, "请求成功", data);
    }

    @Override
    public ApiResponse<Object> addIssue(String issueName) {
        Issue issue = issueMapper.selectOne(new QueryWrapper<Issue>()
                .eq("issue_name", issueName));
        if (issue != null) {
            // 若目标话题已存在，返回204，无事发生
            return new ApiResponse<>(ResponseCode.NO_CONTENT, "请求成功", "话题已存在");
        } else {
            Issue issue1 = new Issue();

            issue1.setIssueName(issueName);
            issue1.setIntroduction("话题默认简介");
            issueMapper.insert(issue1);

            return new ApiResponse<>(ResponseCode.SUCCESS, "请求成功", "新建话题成功");
        }

    }
}
